<?php

namespace App\Http\Middleware;

use App\Models\Member;
use Closure;
use Illuminate\Support\Facades\Cookie;

class Register
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = session('wechat.oauth_user'); // 拿到授权用户资料
        if($user){
            $user = $user->toArray();
            $input = [
                'openid' => $user['id'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar'],
                'sex' => $user['original']['sex']
            ];
            $info = Member::where('openid',$user['id'])->first();
            if(empty($info)){
                $res = Member::create($input);
                if(!$res){
                    return response()->json(['code'=>0, 'msg'=>'微信授权失败']);
                }
            }
        }
        //加入一个微信授权标志,期限2个小时
        Cookie::make('wx_login', md5($user['id']), '120');

        return $next($request);
    }
}
